5.4 MongoDB (v4.2.14 on Ubuntu 24.04)

  1. Motivations
    • Relational databases can hold only relational table data structures, and they cannot support big data well.
    • Is there any other types of database which can support more flexible data structures and big data?
    • How to use MongoDB, one of the most popular NoSQL DBMSes, with Node.js?

  2. Learning outcomes
    • Analyze how MongoDB is different from relational database systems
    • Explain the stucture of databases in MongoDB by comparing it to RDBMS
    • How to connect to MongoDB in a shell and change the user's password
    • How to use basic features of MongoDB with Node.js, i.e., CRUD (Create, Read, Update, Delete) operations?
    • How to solve example problems using MongoDB:
        In a chatting app,
      • Build up a library to support user namagement
      • Data
    • If you are interested in system administration, how to install MongoDB and how to create users

  3. What is MongoDB?
    • Read 'What is a NoSQL database?' and "Types of NoSQL Database' (many more topics) in NoSQL Database Explained and "Key Differences between SQL and NoSQL" in Understanding SQL vs NoSQL Databases.
    • Read the first two paragraphs in MongoDB.
    • Read 'Document Database' in Introduction to MongoDB.
      • What is a record in MongoDB?
      • What is a document in MongoDB?
      • What is a collection in MongoDB?
      • What is a database in MongoDB?
      • What are the advantages of using MongoDB?
    • [You may watch MongoDB Tutorial 1 What is MongoDB?.]
    • Read all in MongoDB Overview. It includes a table of comparison between RDBMS and MongoDB.
      • What is a record in MongoDB?
      • What is a document in MongoDB?
        similar to a JS object (string)
      • What is a collection in MongoDB?
        similar to a JS object (string) of JS objects (strings)
      • What is a database in MongoDB?
      • Comparision
        RDBMSMongoDB
        DatabaseDatabase
        TableCollection - JS object like syntax
        Row (record)Document (record) - JS object, i.e., JSON, like syntax
        ColumnField
        Primary keyDefault key '_id' provided by MongoDB itself
        SQLJS like syntax (But the idea is not much different.)
    • Read all in MongoDB Advantages.
      • What are the advantages of using MongoDB?
    • [You may read all in MongoDB Data Modeling.]
      • Do you need to use multiple collections for a schema?

  4. [You may skip this topic.] How to install MongoDB on Ubuntu?

  5. [You may skip this topic.] User administration
    • Why do you need this?
    • [You may skip this topic.] How to set a system-level user administrator?
      • Read the followings in Enable Access Control to create the system user administrator, "root", right after the installation of MongoDB.
        • Overview
        • User Administrator
        • Procedure: 1 ~ 5
      • Read Procedures 6 ~ 7 in Enable Access Control to create additional users.
        • Starting mongod with the following authorization setting in /etc/mongod.conf.
          security:
              authorization: enabled
          
        • To create additional users, Add Users and Change Your Password and Custom Data. Here is an example how to create a user and how the user changes his/her password.
          $ mongo admin -u root -p
          MaongoDB shell ...
          Enter password:
          > db.createRole(
             { role: "changeOwnPasswordCustomDataRole",
               privileges: [
                  {
                    resource: { db: "", collection: ""},
                    actions: [ "changeOwnPassword", "changeOwnCustomData" ]
                  }
               ],
               roles: []
             }
          )
          > exit
          $ mongo admin -u root -p
          MaongoDB shell ...
          Enter password:
          use dbname
          > db.createUser(
              {
                user: "???",
                pwd: "???",
                roles: [ "readWrite", { role: "changeOwnPasswordCustomDataRole", db: "admin" } ]
              }
          )
          > exit
          $ mongo dbname -u username -p
          MaongoDB shell ...
          Enter password:
          > db.runCommand(
              { updateUser: "test",
                pwd: "newpassword"
              }
          )
          
    • How to connect to the MongoDB shell?
      • Your username for MongoDB is the same as your CS account name. Your initial password is your MongoDB username with '136'. Your database name is COMP4620_yourMongoDBusername.
      • Here is an example how to connect to a database.
        $ mongo databasename -u username -p
        $ mongo [admin] -u root -p
        $ mongo COMP4620_test -u test -p
        
    • [You may skip this topic.] User Management Methods.

  6. How to use?
    • Make a connection
    • CRUD operations
    • Close the connection

  7. How to connect to MongoDB using the MongodB shell?
    • Your username for MongoDB is the same as your CS account name.
      Your initial password is yourMongoDBusername with '136'.
      Your database name is 'COMP4620_yourMongoDBusername'.
    • Here is an example how to connect. You will be asked to enter a password.
      $ mongo databasename -u username -p
      $ mongo COMP4620_yourMongoDBusername -u yourMongoDBusername -p
      
    • Trial 0.1: Let's connect to cs.tru.ca and access to your MongoDB using the MongoDB shell. Try to execute the next shell commands. How to exit from the MongoDB shell?
      • help
      • show dbs
      • show collections
      • show users
      • db
      • exit

  8. How to create a collection and insert documents, and search documents, with the MongoDB shell?
    • Read 'Run Commands' in Run Commands and 'Perform CRUD Operations' in Perform CRUD Operations.
      • How to switch to a database?
      • How to create a collection?
      • How to insert a document into a collection?
      • Here are some examples. You may need to remember that database > collection (table in relational databases) > document (row in ...) > field (column in ...).
        db    // List the current working database
        use mydb    // Change the current working database; db represents the current working database
        help
        show collections    // Show all the collections in db
        j = { name: 'mongo' }
        k = { x: 3, y: j.name }    // j.name?
        db.testData.insertOne(j)    // A collection, testData, will be created if it doest not exist
        db.testData.insertOne(j)    // The same document again?
        db.testData.insertOne(k)
        db.testData.insertOne({course: "COMP4620", user: "Tom"})
        db.testData.find()
        db.testData.find({user:"Tom"})
        db.testData.drop()
        db.createCollection('Users')
        show collections
        exit
        
      • Trial 1: Let's connect to cs.tru.ca and access to your MongoDB. Try the above shell commands and see what happens.
      • Can you insert the same document again?
      • Don't you need a primary key in a collection? If so, what is used as a primary key in a collection?
      • Which shell commands are used to query for specific documents?

  9. How to CRUD (create, read, update, and delete) with the MongoDB shell?
    • If you didn't, read all in MongoDB CRUD Operations, and try all the examples.
      • What method is used to query documents (select in SQL)?
        db.collection.findOne(), db.collection.find()
      • Syntax?
        db.collection.find(...query_criteria...)...modifier...; query_criteria is like a document.
      • List the three operations to modify data in a single collection.
        Insert, delete, update documents.
      • Syntax?
        db.collection.insertOne(...document...), .insertMany(...)
        db.collection.updateOne(...document...), .updateMany(...)
        db.collection.deleteOne(...document...), .deleteMany(...)
      • Comparision
        RDBMSMongoDB
        insertinsertOne(), insertMany()
        selectfindOne(), find()
        updateupdateOne(), updateMany()
        deletedeleteOne(), deleteMany()
    • If you didn't, read all in MongoDB CRUD Tutorials, and try all the examples.
      • Create - Read all in Insert Documents
        • How to insert a document of a username and his/her password into a collection for your Chatting application?
          db.Users.insertOne({username: '...', password: '...', full_name: '...', email: '...'})
          
        • Should there be a unique key in the above document?
        • Can you insert an array? Should the elements in an array be the same structure?
          .insertMany([{...}, ...])
      • Trial 2: Let's try to insert serveral users' information to the collection 'Users' using the MongoDB shell. An example of user's information: username:"skywalker", password:"starwars", email:"Falcon"
      • Read - How to support find/search/select criteria? Read all in Query Documents
        • What does .find() return?
        • How .find() and .findOne() are different?
        • List all the comparison, logical, element, and evaluation query selectors in Query and Projection Operators.
        • Can you compare SQL select to .find()?
          SELECT * FROM table
        • Equality - How to find a document of a username and his/her password in a collection for your Chatting application?
          db.Users.findOne({username: '...', password: '...'})
          
        • How to find all documents having the usernames joined in your Chatting application?
          db.Users.find({username: {$exists: true}})
          
        • How to find all documents having the usernames starting with 'a'? Do you remember Regular Expressions?
          db.Users.find({username: {$regex: /^a/}})  // not in JavaScript?
          db.Users.find({username: /a$/})  // not in JavaScript?
          db.Users.find({username: {$regex: '^a'}})
          db.Memos.find({memo: {$regex:`${search_term}`, $options:'i'}})
          
        • How to find all the documents from the inventory collection, in which the quantity is greater than 20 or the prices is less than or equal to 29.99?
          db.inventory.find({$or: [{quantity: {$gt: 20}}, {price: {$lte: 29.99}}]})
          
        • How to find all the documents from the inventory collection, in which the quantity is greater than 20 and the prices is less than or equal to 29.99?
          db.inventory.find({quantity: {$gt: 20}}, {price: {$lte: 29.99}})  // You can also use $and.
          
        • How to sort the result set? Read Cursor Methods.
          db.inventory.find({quantity: {$gt: 20}}, {price: {$lte: 29.99}}).sort({name: 1})  // 1: ascending order; -1: descending order
          
      • Trial 3: Let's try the above examples with the Users collection.
      • Update - Read all in Update Documents
        • What if any document with that query does not exist?
          Do nothing by default
        • How can you change a user's password for your Chatting application?
          db.Users.updateMany({username: '...'}, {$set: {password: '...'}})
          
        • How can you rename a field name in a document?
          $rename update operator
        • How can you delete a field?
          The $unset operator
      • Trial 4: Let's try to update the Users collection with username:"skywalker". Maybe wth a different password?
      • Delete - Read all in Delete Documents
        • How can you delete a user name and her/his password for your Chatting application?
          db.Users.deleteMany({username: '...'})
          
        • Can you delete all documents in a collection?
        • Can you drop a collection?
          db.collection.drop()
          
        • Can you delete all collections in a database?
        • Can you drop a database?
          db.dropDatabase()
          
      • Trial 5: Let's try to delete some documents in the Users collection. Maybe username:"skywalker"?
      • Here is a link for all the MongoDB shell methods - mongo Shell Methods.
    • Here is another good reference for CRUD - tutorialpoint - MongoDB Tutorial.

  10. How to use MongoDB with Node.js? How to solve an example problem: User management in applications?
    • Read 'A Basic Introduction to Mongo DB' in A Basic Introduction to Mongo DB.
      • There are some Node.js modules to access MongoDB. They are called MongoDB drivers.
      • Which driver is used in the above link?
      • Can we use async-await instead of callback functions?
    • Read 'Mongo DB data types' in A Basic Introduction to MongoDB.
      • What data types are supported?

    • Read 'Getting that connection to the database' in A Basic Introduction to MongoDB.
      • If necessary, install the 'mongodb@4.17.2' module as follows. (Not the lastest version; 4.17.2 to support MongoDB v4.2.14 currently running on cs.tru.ca.) In the current working directory,
        1. If the directory, node_modules, does not exist, create it.
          $ mkdir node_modules
        2. Install a mongodb driver. The driver will be installed in node_modules in the current working directory.
          $ npm install mongodb@4.17.2
        3. Let's make all the subdirectories and files in node_modules readable to all accounts on cs.tru.ca as follows. It is necessary when sjs programs are executed from the client-side using the instructor's Node Web Server of port number 8080.
          $ ~mlee/bin/chr node_modules
    • Here is an example to connect to your DB, which uses a callback function. You need to use a URL, mongodb://username:password@server[:port]/databasename, to make a connection.
      const MongoClient = require('mongodb').MongoClient;
      
      // mongodb://username:password@server[:port]/databasename
      MongoClient.connect('mongodb://???:???@127.0.0.1:27017/???',  
        function(err, conn) {  // What is '127.0.0.1'? Any security issue?
                               // conn is a connection stub used for CRUD operations.
          if(err) throw err;
          
          console.log("MongoDB connected");
          // What if conn.close() is here?
          conn.close();
      });
      
    • (The above example may not work properly. Probably, it is because the latest "mongodb' module, not mongodb@4.17.2, is installed and used.) Let's use the async/await version instead. Read Connection Guide.
    • Here is an example that uses async/await.
      const MongoClient = require('mongodb').MongoClient;
      
      (??? function() {
          try {
              const conn = ??? MongoClient.???('mongodb://youraccount:password@127.0.0.1:27017/yourdbname');
              console.log("MongoDB connected");
              conn.close();
          }
          catch(err) {
              console.log(err);
          }
      })();  // self invocation of an anonymous function
      
    • Trial 6: Let's try the above code with your MongoDB account. You can save the code in test.js, and run the program on the PuTTy terminal.
    • Trial 7: As shown in the next example code, let's revise the code and save it in userManagement.sjs under ~youraccount/pulic_html, so that the program can be executed with your Node web server or the instructor's Node web server. (You may try with http://cs.tru.ca:8080 and /~mlee/comp4620/Winter2025/5.%20back_end_technologies/userManagement.sjs. You can test your userManagement.sjs file. But don't forget to set proper accessibility on directories and files.)
      const MongoClient = require('mongodb').MongoClient;
      
      const ??? = ??? function(_GET, _POST, callback)  {  // This function should pass a string message back through callback.
          try {
              // mongodb://username:password@127.0.0.1[:port]/databasename
              const conn = ??? MongoClient.???("mongodb://????@127.0.0.1:27017/???");
              conn.???();  // It is a must. Otherwise, the max number of connections will be fed up. Why?
              ???("MongoDB connected using async/await");
          } 
          catch(err) {
              callback('Connection error');
          }
      }
      
      ????
      
    • Now we know how to make a connection to a MongoDB with Node.js. What next?

  11. Read 'Mongo DB and Collections' in Mongo DB and Collections and Node.js MongoDB Create Collection.
    • General steps:
      • conn stub from MongoClient.connect(...)
      • db stub from conn.db()
      • collection stub from db.collection(...)
      • CRUD operations with the collection stub
      • Close the connection.
    • How to create a collection? Which method is used?
    • How to use a collection?
    • The next example shows how to create a collection if the collection does not exist.
      const MongoClient = require('mongodb').MongoClient;
      
      (async function() 
      {
          try {
              // connection stub
              const conn = await MongoClient.connect(????);
              console.log("MongoDB connected");
              
              // db stub
              let db = conn.???();
              
              // If the "Users" collection does not exist, let's create it.
              let list = await db.listCollections().toArray();
              let exist = false;
              for (let i = 0; i < list.length; i++) {
                  if (list[i].name == "Users") {
                      exist = true;
                      break;
                  }
              }
              if (!exist) {
                  await db.createCollection("Users");
                  console.log("Users created");
              } else
                  console.log("Users exists");
                  
              // collectin stub
              let collection = db.???("Users");
              
              // find all documents in the collection
              let lists = await collection.????.toArray();
              console.log(lists);
              
              // close the connection to MongoDB
              conn.close();
          }
          catch(err) {
              console.log(err);
              conn.close();
          }
      })();  // self invocation of an anonymous function
      
    • Trial 7.5: Save the above code in test.js, and test it on cs.tru.ca. How to check if the Users collection is created?
    • What if we try to insert a document into a collection that does not exist?
    • How to drop a collection?
    • What is next?

  12. Read 'And then there was CRUD' in And then there was CRUD.
    • What are the four basic operations?
        The next examples use callback functions. We can use async-await instead.
      • collection.insertOne|insertMany(..., {w:1}, function(err, result) { ... }) // the w option to request acknowledgment; See Write Concern for {w:1}.
      • collection.findOne(..., function(err, item) { ... });
      • collection.find(...).toArray(function(err, items) { ... });
      • collection.updateOne|updateMany(..., {$set:...}, {w:1}, function(err, result) { ... });
      • collection.deleteOne|deleteMany(..., {w:1}, function(err, result) { ... });
    • The MongoDB driver does NOT support synchronous operations, not like the above link explains.
    • How to find multiple documents?
    • What if you have a big find result set?

  13. Considerations for UserManagement in applications
    • Collection: Users
    • Join - What kind of CRUD operations are required? .findOne() or .find(), insertOne()
    • Delete a user's profile - .deleteOne()
    • Chage a user's profile - .updateOne()
    • Sign in - .findOne()
    • Sign out

  14. Create - Node.js MongoDB Insert
    • Join - How to check if a username exists in the collection, "Users"?
      const MongoClient = require('mongodb').MongoClient;
      
      const usernameExists = ??? function(???, callback)
      {
          ????
          let collection = db.???("Users");
          
          let list = ??? ????(????);
          if (????)
              callback(true);
          else
              callback(false);
      
          conn.close();
      }
      
      // code to test the above function
      let username = "tom";
      usernameExists(???, function(result) {
          console.log("tom: " + result);
      });
      username = "john";
      usernameExists(???, function(result) {
          console.log("john: " + result);
      });
      
    • Trial 8: Let's complete the above code, that uses a function, in test.js and test it on cs.tru.ca. This function uses a callback function to pass true or false back. (Do you think you can rewite the above code so that async-await is used instead of callback functions?)

    • Join - How to register a new user's profile (i.e., username and password) into "Users", when the username does not exist?
      (Note that if the 'Users' collection does not exist, it will be created when a document is inserted.)
      What kind of document you want to insert? This is an important design issue.
      const MongoClient = require('mongodb').MongoClient;
      
      const registerUser = ??? function(???, ???, callback) 
      {
          try {
              ????
              let collection = db.collection("Users");
              ??? ???.???(????);
              ????
              conn.close();
          }
          catch(err) {
              callback(false);
              conn.close();
          };
      }
      
      // code to test the above function
      registerUser("john", "topoftheworld", ???? {
          console.log(result);
      });
      
    • Trial 8.5: Let's add the above code in test.js and complete/test it on cs.tru.ca.

  15. Read - Node.js MongoDB Find, Node.js MongoDB Query, Node.js MongoDB Sort
    • Sign In - How to check if a document of username and password exists in the collection, 'Users'?
      const MongoClient = require('mongodb').MongoClient;
      
      const validateUsernamePassword = ??? function(username, password, callback)
      {
          ????
          
          let list = ??? ????(????);  // findOne() or find().toArray()
          if (????)
              callback(true);
          else
              callback(false);
      
          conn.close();
      }
      
      // code to test the above function
      let username = "tom";
      let password = "topsecretpassword";
      validateUsernamePassword(???, ???, function(result) {
          console.log("tom: " + result);
      });
      username = "john";
      password = "topoftheworld";
      validateUsernamePassword(???, ???, function(result) {
          console.log("john: " + result);
      });
      
    • Trial 9: Let's add the above code in test.js and complete/test it on cs.tru.ca.

  16. Delete - Node.js MongoDB Delete, Node.js MongoDB Drop,
    • Delete a user's profile - How to delete all documents that have a given username from the collection, 'Users'?
      const deleteUser = ??? (username, callback) =>  // You need to include the next code with the connection to MongoDB.
      {
          ????
          
          ????  // deleteOne() or deleteMany()
          let list = ??? ????(????);  // findOne() for testing
          if (????)
              callback(true);
          else
              callback(false);
      
          conn.close();
      }
      
      let username = "tom";
      deleteUser(???, function(result) {
          console.log(result);
      });
      
    • Trial 10: Let's add the above code in test.js and complete/test it on cs.tru.ca.

  17. Update? Read all in Node.js MongoDB Update.
    • Can you implement a function to update a user's information in "Users"? For example, new password or email address.
    • Trial 10.5: Let's write the code in test.js and test it on cs.tru.ca.

  18. How to solve an example problem: User management in a chatting app?
    • Chatting app: How to do "Join"?
    • Chatting app: How to do "SignIn"?
    • Chatting app: How to do "Delete"?
    • Here is an example. TRU Chatting (http://cs.tru.ca:8080/...) uses chat_controller.sjs and chat_model.js. chat_controller.sjs is a server-side program, and chat_model.js is a library (i.e., module) that includes functions to access MongoDB. chat_model.js is used in chat_controller.sjs. Try the app to see how it works, and read the code to see how chat_controller.sjs is used.

    • Something to think about in chat_model.js:
      Note that the chat server (i.e., chat_controller.sjs) needs to keep the connection to MongoDB for a long time.
      How to keep one connection for usernameExists(), registerUser(), validateUsernamePassword(), updateUser(), and deleteUser() that were developed in multiple previous Trials?
      An idea that we use is similar to $(document).ready(function() { ... });.

    • Let's consider chat_contorller.sjs first as follows.
      model is required from chat_model.js, and this module has a method ready(). When the model is ready (i.e., ready() passes true back,) the methods in UserManagement can be invoked. Any idea how to use read()?
      // In chat_controller.sjs program, how to use chat_model.js?
      
      // If Model were revised, the cached Model module may need to be deleted.
      delete require.cache[require.resolve("./chat_model.js")];
      const model = require("./chat_model.js");
      
      const proceed = function(_GET, _POST, callback)
      {
          ...
          // For Join
          model.ready(function(result) {
              if (result)
                  model.usernameExists(_POST['username', function(result) {
                      ...
                  });
          });
          ...
          
          // For SignIn
          model.ready(function(result) {
              if (result)
                  model.validateUsernamePassword(_POST['username'], _POST['password'], function(result) {
                      if(result) callback("true");
                      else callback("false");
                  });
          });
          
          ...
          model.close();  // It is required.
          ...
      }
      ...
      

    • chat_model.js - Let's read the code carefully.
      // All functions pass back a Boolean value - true or false.
      
      let MongoClient;
      let conn;  // connection stub
      let db;  // db stub
      let collection;  // collection stub
      let connected = false;  // flag to see if a connection is made
      
      // Prepares conn, db, collecton, connected
      // Passes true|false back through a callback function
      const ready = async function(callback)
      {
          if (???) callback(true);
              
          else {
              try {
                  // connection
                  MongoClient = require("mongodb").MongoClient;
                  conn = await MongoClient.connect(????);
                  
                  // db stub
                  db = ????;
                  
                  /* It is unnecessary.
                  // If the "Users" collection does not exist, let's create it.
                  let list = await db.listCollections().toArray();
                  let exist = false;
                  for (let i = 0; i < list.length; i++) {
                      if (list[i].name == "Users") {
                          exist = true;
                          break;
                      }
                  }
                  if (!exist)
                      await db.createCollection("Users");
                  */
                  
                  // collection stub
                  collection = ????("Users");
                  
                  // return ... through the callback function
                  ????
                  callback(???);
              }
              catch(err) {
                  connected = false;
                  callback(false);
              }
          }
      }
      
      const close = function() {
          if (???) {
              connected = ???;
              conn.close();
          }
      }
      
      const usernameExists = ??? function(u, callback)
      {
          try {
              let list = ????
              if (????)
                  callback(true);
              else
                  callback(false);
          }
          catch(err) {
              callback(false);
          }
      }
      
      ????
      
      exports.ready = ready;
      exports.close = close;
      exports.usernameExists = usernameExists;
      exports.registerUser = registerUser;
      exports.validateUsernamePassword = validateUsernamePassword;
      exports.updateUser = updateUser;
      exports.deleteUser = deleteUser;
      

    • Trial 11. For the user management, TRU Chatting uses chat_controller.sjs and chat_model.js. Try it to see how the above code works. (Note that the above Chat App uses the HTTP POST method.)
      • Copy the above client-side app code to view_chat_startpage.html in your test directory under public_html.
      • Complete chat_model.js
      • Complete chat_contorller.sjs
      • Test view_chat_startpage.html with "http://198.162.21.132:8080/..."
      • Commands from the client:
        • SignIn: page:StartPage; command:SignIn; username:...; password:...
        • Join: page:StartPage; command:Join; username:...; password:...
        • Delete: page:StartPage; command:Delete; username:...; password:...
        • Close: page:StartPage; command:Close

    • A challenge. Can you develop an express app server that includes main operations (i.e., Join, SignIn, SignOut, Change, Delete) in chat_controller.sjs?

    • Trial 11.5. What if .close() is not invoked from application code? The connection to MongoDB will not be closed as long as the app process is alive. Note that the server-side JS app is executed from the Node WebServer, and the app will not be terminated becase the web server is always alive. This will make the number of connections to MongoDB grow indefinitely and a huge trouble. How to resolve this problem? Let's include a timer in .ready() and .close(), and let's test the chat app again.
      ...
      let timerid;
      
      const ready = async function(callback)
      {
          if (connected) callback(true);
              
          else {
              try {
                  // connection
                  MongoClient = require("mongodb").MongoClient;
                  conn = await MongoClient.connect(????);
                  // 1 second timer to close
                  ???? // clear the timer
                  timerid = ???(() => {  // re-start the timer
                      close();
                  }, 1000);
                  ...
              }
              catch(err) {
                  ...
              }
          }
      }
      
      const close = function() {
          if (connected) {
              conn.close();
              connected = false;
              // clear the timer
              ???(timerid);
          }
      }
      

  19. Don't you need to encrypt password before you save it in a db?
    • Read all in Encrypt and decrypt content with Node.js.
    • Meaning of encryption, decryption, hashing, block cipher, operation mode, initial vector, ...?
    • Read all in SHA 512 Hashs with Node.js.
    • Can you use the user's password as the password to encrypt or hash the user's password?
    • Here is an example of using HMAC (a keyed-hash message authentication code).
      var crypto = require('crypto');
      
      // create hmac
      var hash = crypto.createHmac('sha512', 'topsecretkey');  // sha1, md5, sha256, sha512, ...
                                                               // It requires a key.
                                                               // Is it a good idea for your chatting program?
      hash.update('Good morning, Dave!');
      hash.update('Good morning, HAL!');
      var value = hash.digest('hex');  // hex, binary, or base64
      
      // print result
      console.log(value);
      
    • Trial 12. Try the above code in the Node console.
    • Do you have to use a key to hash a user's password? Here is an example of using hash, not hmac.
      var crypto = require('crypto');
      
      // create hash
      var hash = crypto.createHash('sha512');  // sha1, md5, sha256, sha512, ...
                                               // No key is required.
                                               // How to use this for your chatting program?
      hash.update('Good morning, Dave!');
      hash.update('Good morning, HAL!');
      var value = hash.digest('hex');  // hex, binary, or base64
      
      // print result
      console.log(value);
      
    • Trial 12.5. Try the above code in the Node console.
    • Trial 13. Let's include the use of encrypted passwords in chat_model.js.
    • Can you now store the user's encrypted (i.e., hashed) password into a database?
    • Here is the full documentation for the Node.js crypto module - Node.js v0.10 Manual & Documentation.

  20. How to close the db?
    db.close();  // When do you close?
    

  21. References for further information